package com.Servlet;

import com.Bean.UserCounter;
import com.Objects.User;
import com.Service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        response.setContentType("text/html; charset=UTF-8");
        User user = UserService.Login(username, password);

        if (user != null) {
            request.getSession().setAttribute("username", username);
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
            UserCounter userCounter = (UserCounter) applicationContext.getBean("user-counter");
            request.getSession().setAttribute("usernumber", userCounter.GetUserNumber() + 1);
            response.getWriter().write(
                    "<script language='javascript'>" +
                            "alert('登录成功');" +
                            "window.location.href='./index.jsp';" +
                            "</script>");
        } else {
            response.getWriter().write(
                    "<script language='javascript'>" +
                            "alert('登录失败');" +
                            "window.location.href='./login.jsp';" +
                            "</script>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
